package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存双向好友关系
    public void save(Long userId, Long friendId) {
        //判断userId到friendId的好友关系是否存在，不存在保存

        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query1 = Query.query(criteria1);
        if(!mongoTemplate.exists(query1, Friend.class)) {
            //1、保存userId到friendId的好友关系
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        //判断friendId到userId的好友关系是否存在，不存在保存
        Criteria criteria2 = Criteria.where("friendId").is(userId).and("userId").is(friendId);
        Query query2 = Query.query(criteria2);
        if(!mongoTemplate.exists(query2, Friend.class)) {
            //2、保存friendId到userId的好友关系
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    //分页查询好友列表
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Friend.class);
    }
}
